package com.wephone.Student.ui;

import java.io.File;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioButton;

import com.wephone.Student.R;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.Util;

public class NewRegisterActivity2 extends BaseActivity{
	private int _year;
	private int _month;
	private int _day;
	private TextView birthEdit;
	private EditText signatrueEdit;
	private String uPlatform;
	private String uPlatformid;
	private String gender;
	private String username;
	private String password;
	private String nick;
	private File photoSavedFile = null;
	private String photoSavedName = null;
	private ImageView userPhoto;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1){
			if(photoSavedFile!=null && photoSavedFile.exists()){
				Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile.getPath(),300);
       		 	userPhoto.setImageBitmap(bitmap);
       		 	Util.saveMyBitmap(bitmap,photoSavedName,getApplicationContext());
			}else if(data!=null){
				Bundle bundle = data.getExtras();
				if(bundle!=null){
					Bitmap tmpbitmap = (Bitmap)bundle.get("data");
					if(tmpbitmap!=null){
						userPhoto.setImageBitmap(tmpbitmap);
		       		 	Util.saveMyBitmap(tmpbitmap,photoSavedName,getApplicationContext());
					}
				}
			}
   	 	}else if(requestCode==2){
	   	 	if(data!=null){
	   		 	Uri selectedImage = data.getData();
		        String[] filePathColumn = {MediaStore.Images.Media.DATA};
		        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
		        cursor.moveToFirst();
		        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		        String picturePath = cursor.getString(columnIndex);
		        cursor.close();
		        if(!TextUtils.isEmpty(picturePath)){
		        	 File userLogoFile = new File(picturePath);  
		        	 if(userLogoFile.exists()){
		        		 Bitmap bitmap = Util.getBitmap(getApplicationContext(),picturePath,300);
		        		 userPhoto.setImageBitmap(bitmap);
		        		 Util.saveMyBitmap(bitmap,photoSavedName,getApplicationContext());
		        	 }
		         }
	   	 	}
   	 	}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_register_2);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			uPlatform = bundle.getString("uPlatform");
			uPlatformid = bundle.getString("uPlatformid");
			gender = bundle.getString("gender");
			username = bundle.getString("username");
			password = bundle.getString("password");
			nick = bundle.getString("nick");
			
			if(!TextUtils.isEmpty(gender)){
				if(gender.equals("1")){
					((RadioButton)findViewById(R.id.gender_radio_1)).setChecked(true);
				}
			}
			if(!TextUtils.isEmpty(nick)){
				((TextView)findViewById(R.id.user_name_text)).setText("Hello，"+nick);
			}
		}
		init();
		
	}
	
	private void init(){
		_year = 1990;
		_month = 1;
		_day = 1;
		birthEdit = (TextView)findViewById(R.id.user_birth_edit);
		signatrueEdit = (EditText)findViewById(R.id.user_signature_edit);
		userPhoto = (ImageView)findViewById(R.id.user_logo_image);
		
		birthEdit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showChooseDateDialog();
			}
		});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		OnClickListener onClickListener = new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(NewRegisterActivity2.this).setTitle("选择头像")
				.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						String pathString;
						if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
				        {
							
							pathString = Constants.IMAGE_PHOTO_TMP_PATH;
				        }else{
				        	
				        		pathString = NewRegisterActivity2.this.getCacheDir().getAbsolutePath()+"/";
				        }
						if(arg1==0){
							File rootFile = new File(Constants.IMAGE_PHOTO_TMP_PATH);
							if(!rootFile.exists()){
								rootFile.mkdirs();
							}
							photoSavedName = "userlogo_"+System.currentTimeMillis()+".jpg";
							
							photoSavedFile = new File(pathString+photoSavedName);
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile));
		                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		                    startActivityForResult(intent, 1);
						}else{
					
							photoSavedName = "userlogo_"+System.currentTimeMillis()+".jpg";
							photoSavedFile = new File(pathString+photoSavedName);
							Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							startActivityForResult(i, 2);
						}
					}})
				.setNegativeButton("取消", null).show();
			}
		};
		findViewById(R.id.btn_camera).setOnClickListener(onClickListener);
		findViewById(R.id.user_logo_image).setOnClickListener(onClickListener);
		
		findViewById(R.id.btn_next_step).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(TextUtils.isEmpty(birthEdit.getText().toString())){
					Toast.makeText(getApplicationContext(), "请选择出生日期", Toast.LENGTH_SHORT).show();
					return;
				}
				if(photoSavedFile==null || !photoSavedFile.exists()){
					Toast.makeText(getApplicationContext(), "请设置用户头像", Toast.LENGTH_SHORT).show();
					return;
				}
				
				Bundle bundle = new Bundle();
				bundle.putString("username", username);
				bundle.putString("password", password);
				bundle.putString("nick", nick);
				bundle.putString("uPlatform", uPlatform);
				bundle.putString("uPlatformid", uPlatformid);
				bundle.putString("signature", signatrueEdit.getText().toString());
				bundle.putInt("year", _year);
				bundle.putInt("month", _month);
				bundle.putInt("day", _day);
				if(((RadioButton)findViewById(R.id.gender_radio_1)).isChecked()){
					bundle.putString("gender", "0");
				}else{
					bundle.putString("gender", "1");
				}
				bundle.putString("photoSavedPath", photoSavedFile.getPath());
				startActivity(new Intent(getApplicationContext(),NewRegisterActivity3.class).putExtras(bundle));
			}
		});
		
	}
	
	private void showChooseDateDialog(){
		new DatePickerDialog(this, new OnDateSetListener() {
            public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                _year = year;
                _month = monthOfYear;
                _day = dayOfMonth;
                birthEdit.setText(_year+"年"+(_month+1)+"月"+_day+"日");
            }

        }, _year, _month, _day).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true; 
       }
       return super.onKeyDown(keyCode, event);
	}
	
}
